<?php
namespace models;

class points
{

    // 批量加分的公用函数
    public function add($sites, $class_id, $point, $reason, $task_id)
    {
        $ignoreStu = '';
        $sites    = explode('.', $sites);
        foreach ($sites as $v) {
            // 查询是否有此学生
            $stu   = db('students')->where('class_id=? and site=?', [$class_id, longSite($v)])->fetch('id');
            $stu_id = $stu['id'];

            //查询这节作业没加过分,才加
            $r = db('points')->where('stu_id=? and task_id=? and type=?', [$stu_id, $task_id, '作业加分'])
                ->fetch();

            if ($r === false) {
                //新增积分记录
                db('points')->add(['stu_id' => $stu_id, 'task_id' => $task_id, 'type' => '作业加分', 'point' => $point, 'reason' => $reason]);
                db('students')->where('class_id=? and site=?', [$class_id, longSite($v)])->field('task_point', $point);
                db('students')->where('class_id=? and site=?', [$class_id, longSite($v)])->field('game_point', $point);

            } else {
                // 将加分失败的座位号返回, 这部分已经加过分的不加,但是要提示
                $ignoreStu = $ignoreStu . ',' . $v . '号';
            }
        }

        if ($ignoreStu !== '') {
            $ignoreStu = substr($ignoreStu, 1); //去掉最前面的,号
        }
        return $ignoreStu;

    }

// 取班级或单个学生的积分记录
    public function get($bj, $type = null, $stu_id = null, $begin, $limit)
    {
        $join = 'as a
                    left join tb_tasks as b on a.task_id=b.id
                    left join tb_categorys as c on b.category_id=c.id
                    left join tb_students as  d on a.stu_id=d.id';

        $column = 'a.created,a.type,a.point,a.reason,b.name as task_name,c.name as category_name,d.name as stu_name,d.site as site';
        $order  = 'a.created desc';
        $w1     = ''; //条件的第1部分
        $w2     = ''; //条件的第2部分

        if ($stu_id != null) {
            //某个学生的记录
            $w1 = 'a.stu_id=? and a.type like ?';
            $w2 = [$stu_id, '%' . $type . '%'];
        } else {
            //某个班级的记录
            $w1 = 'd.class_id=? and a.type like ?';
            $w2 = [$bj, '%' . $type . '%'];
        }


        $r   = db('points')->join($join)->where($w1,$w2)->fetchAll("count('a.*') as total");
        // $r=db('points')->query('select count(*) from tb_points ? where ? = ?',[$join,$w1,$w2]);
        $count=$r[0]['total'];
        //$count = count($r1); //符合条件的记录数
        $r2    = db('points')->join($join)->where($w1, $w2)->limit($begin, $limit)->order($order)->fetchAll($column);
        if ($count > 0) {
            $data['data']  = $r2;
            $data['count'] = $count;
            $data['code']  = 0;
        } else {
            $data['msg'] = '无相关记录';
        }
        json($data);

    }
}
